package com.ahuan.controller;

import com.ahuan.domain.Product;
import com.ahuan.exception.BusinessException;
import com.ahuan.resp.Res;
import com.ahuan.service.GoodsService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;


@Slf4j
@RestController
@RequestMapping("/api/Goods")
public class GoodController {

    @Autowired
    GoodsService goodsService;


    @PostMapping("/list")
    public Res getGoodsList(Integer page, Integer limit) {
        try {
            log.info("page:{},limit:{}", page, limit);
            List<Product> list = goodsService.queryGoodsList(page, limit);
            if (list == null) {
                return Res.failOperate();
            }
            return Res.successOperate(list);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("获取商品库存列表失败");
        }
    }


    @PostMapping("/save")
    public Res saveGoods(@RequestParam("images") MultipartFile[] imgs, Product product) {
        try {
            String userId = MDC.get("userId");
            String userName = MDC.get("userName");
            product.setCreateUser(Long.parseLong(userId));
            product.setUpdateUser(Long.parseLong(userId));
            log.info("imgs:{}", imgs);
            String imgUrl = null;// todo 优化成图片数组
            if (imgs.length > 0) {
                for (MultipartFile img : imgs) {
                    imgUrl = saveImg(img);//将图片保存到static目录下
                }
            }
            product.setImg(imgUrl);//设置图片路径
            log.info("product:{}", product);
            if (product.getId() == null) {
                log.info("{}请求新增商品信息,商品信息:{}", userName, product);
                if (goodsService.saveGoods(product)) {
                    return Res.successOperate();
                }
                return Res.failOperate();
            } else {
                log.info("{}请求修改商品信息,商品信息:{}", userName, product);
                if (goodsService.saveGoods(product)) {
                    return Res.successOperate();
                }
                return Res.failOperate();
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("商品信息保存失败");
        }
    }



    private String saveImg(MultipartFile img) throws IOException {
        String fileName = img.getOriginalFilename();
        String dir = getClass().getClassLoader()
                .getResource("static").getPath();//获取项目类路径下的static目录
        dir = dir.substring(1).replace("/", "\\") + File.separator;//处理目录
        Path targetLocation = Paths.get(dir + fileName);
        if (!Files.exists(targetLocation.getParent())) {// 如果目标目录不存在，则创建
            Files.createDirectories(targetLocation.getParent());
        }
        img.transferTo(targetLocation);
        return "/api/images/" + fileName;//返回图片URL
    }


    @PostMapping("/save2")
    public Res saveGoods2(Product product) {
        try {
            String userId = MDC.get("userId");
            String userName = MDC.get("userName");
            product.setCreateUser(Long.parseLong(userId));
            if (product.getId() == null) {
                log.info("{}请求新增商品信息,商品信息:{}", userName, product);
                if (goodsService.saveGoods(product)) {
                    return Res.successOperate();
                }
                return Res.failOperate();
            } else {
                log.info("{}请求修改商品信息,商品信息:{}", userName, product);
                if (goodsService.saveGoods(product)) {
                    return Res.successOperate();
                }
                return Res.failOperate();
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            throw new BusinessException("商品信息保存失败");
        }
    }

    @DeleteMapping("/delete")
    public Res deleteGoods(@RequestParam("ids") Long id) {
        log.info("{}请求删除商品信息,商品ID:{}", MDC.get("userName"), id);
        if (goodsService.deleteGoods(id)) {
            return Res.successOperate();
        }
        return Res.failOperate();
    }

    @PostMapping("/upload")
    public Res uploadFile(@RequestParam("file") List<MultipartFile> files) {
        // 保存文件
        try {
            log.info("{}请求上传文件,文件名:{}", MDC.get("userName"), files.size());
            if (files == null || files.isEmpty()) {
                return Res.failOperate();
            }
            boolean b = goodsService.saveFiles(files);
            return b ? Res.successOperate() : Res.failOperate();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("文件上传失败");
        }
    }

    @GetMapping("/download")
    public void downloadFile(HttpServletResponse res) {
        // 保存文件
        try {
            log.info("{}请求导出文件", MDC.get("userName"));
            //设置响应格式
            res.setContentType("application/vnd.ms-excel");

            //得到输出流对象
            OutputStream outputStream = res.getOutputStream();
            // 定义一个文件输出流
//            OutputStream outputStream = new FileOutputStream("D:\\test1\\test.xlsx");
            List<Product> list = goodsService.queryGoodsList(1, 1000);
            res.setContentType("application/vnd.ms-excel;chartset=utf-8"); //文件扩展名为excel格式
            res.setHeader("Content-Disposition", "attachment;filename=test.xlsx");


//           1.
            // 创建一个ExcelWriter对象
            ExcelWriter excelWriter = EasyExcel.write(outputStream).build();
            // 创建一个工作表对象
            WriteSheet sheet = EasyExcel.writerSheet(0, "Sheet").head(Product.class).build();
            // 往 excel 中写入数据

            excelWriter.write(list, sheet);
            excelWriter.finish();

//            res.addHeader("Access-Control-Expose-Headers", "Content-disposition");
//          2.
//            EasyExcel.write(res.getOutputStream(), Product.class) //（输出流， 文件头）
//                    .excelType(ExcelTypeEnum.XLSX)
//                    .autoCloseStream(true)
//                    .sheet("test") //第一个sheet的名
//                    .doWrite(list); //写入数据


//            return Res.successOperate();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("文件导出失败");
        }
    }


    @GetMapping("/barcode")
    public void GetBarcode(@RequestParam Long id, HttpServletResponse res) {

        log.info("id:{}", id);

        String code = "15644646523165462124648";// todo 后面再优化
        try {
            // 要编码为条形码的内容
            String barcodeContent = id + "-" + code;

            // 使用ZXing库生成条形码
            BitMatrix bitMatrix = new MultiFormatWriter().encode(barcodeContent, BarcodeFormat.CODE_128, 600, 100);

            // 将 BitMatrix 转换为 BufferedImage
            BufferedImage image = this.toBufferedImage(bitMatrix);

            // 将 BufferedImage 转换为字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "png", res.getOutputStream());
//            byte[] imageBytes = outputStream.toByteArray();
//            System.out.println(imageBytes.toString());
//            // 返回包含条形码图片字节数组的 ResponseEntity
//            return Res.successOperate(imageBytes);
        } catch (Exception e) {
            e.printStackTrace();
//            return Res.failOperate();
        }
    }

    // 将 BitMatrix 转换为 BufferedImage
    private BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? 0x000000 : 0xFFFFFF);
            }
        }
        return image;
    }


    @GetMapping("/ruku")
    public Res ruku(@RequestParam("code") String code, @RequestParam("num") Integer num) {
        try {
            log.info("code: {},num：{}", code, num);
            String[] split = code.split("-");
            List<Product> list = goodsService.ruku(split[0], split[1], num);
            if (list != null) {
                Res res = Res.successOperate(list);
                System.out.println(res.getData());
                return res;
            }
            return Res.failOperate("库存不足");
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("出入库失败");
        }
    }


//    public static void main(String[] args) {
//        String code = "123"; // 你的条形码内容
//        try {
//            // 要编码为条形码的内容
//            String barcodeContent = 45 + code;
//
//            // 使用ZXing库生成条形码
//            BitMatrix bitMatrix = new MultiFormatWriter().encode(barcodeContent, BarcodeFormat.CODE_128, 250, 100);
//
//            int width = bitMatrix.getWidth();
//            int height = bitMatrix.getHeight();
//            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//            for (int x = 0; x < width; x++) {
//                for (int y = 0; y < height; y++) {
//                    image.setRGB(x, y, bitMatrix.get(x, y) ? 0x000000 : 0xFFFFFF);
//                }
//            }
//
//            // 将 BufferedImage 保存为文件（这里保存为 PNG 格式）
//            ImageIO.write(image, "png", new File("D:\\Javalesson\\springboot项目\\springboot-project\\src\\main\\resources\\static\\barcode.png"));
//
//            System.out.println("条形码图片已生成：barcode.png");
//        } catch (Exception e) {
//            e.printStackTrace();
//            System.out.println("生成条形码图片时出现异常");
//        }
//    }

}


